import axios from "axios";
import router from "../router";
import store from "../store";
import { Message } from "element-ui";
import { removeToken } from "@/utils/auth"; // get token from cookie
import { getToken } from "@/utils/auth";
// create an axios instancep
const service = axios.create({
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 40000, // request timeout
});
const whiteParMap = {
  "api/auth/login": true,
  "api/vehicleMeasurementDetail/delete": true,
  "api/vehicleMeasurementExcel/delete": true,
  "api/dict/delete": true,
  "api/vehicleMeasurementDemand/delete": true,
  "api/vehicleMeasurementTask/delete": true,
  "api/device/delete": true,
  "api/borrower/delete": true,
};
const changeRequestParams = (data = {}) => {
  const par = JSON.parse(JSON.stringify(data));
  const { limit, offset } = par;
  if (limit !== undefined && offset !== undefined) {
    delete par.limit;
    delete par.offset;
    return {
      limit,
      offset,
      data: par,
    };
  }
  return {
    data,
  };
};
service.interceptors.request.use((config) => {
  // responseType
  try {
    const { data, url } = config;
    config.headers["Authorization"] = getToken();
    // if (!whiteParMap[url] && data.data === undefined) {
    //   config.data = changeRequestParams(data);
    // }
    return config;
  } catch (error) {
    return config;
  }
});
// response interceptor
service.interceptors.response.use(
  (res) => {
    const { data } = res;
    if (data != null) {
      const { result, message } = data;
      if (result !== 0) {
        if (result == 401) {
          // 登录失效时重定向
          Message({
            message: "权限已失效，请重新登录！",
            type: "error",
            duration: 5000,
          });
          removeToken();
          store.commit("user/SET_ID", 0);
          router.replace("/login");
          return Promise.reject(res);
        }
        Message({
          message,
          type: "error",
          duration: 5000,
        });
        return Promise.reject(res);
      }
    }
    return data;
  },
  (error) => {
    console.log(error.response.status);
    if (error.response && error.response.status == 401) {
      // 登录失效时重定向
      Message({
        message: "权限已失效，请重新登录！",
        type: "error",
        duration: 5000,
      });
      removeToken();
      store.commit("user/SET_ID", 0);
      router.replace("/login");
      return Promise.reject(res);
    } else {
      Message({
        message: "网络不佳",
        type: "error",
        duration: 5000,
      });
    }
    return Promise.reject && Promise.reject(error);
  }
);

export default service;
